/* eslint-disable react-hooks/rules-of-hooks */
import React, { forwardRef, useState, useRef, useImperativeHandle, useEffect } from 'react';
import styles from './style.less';
import { PageContainer } from '@ant-design/pro-layout';
import { EllipsisOutlined } from '@ant-design/icons';
import { ProColumns, ProTable, ProDescriptions } from '@ant-design/pro-components';
import { Button, Space, Drawer, Tag, Popconfirm, message } from 'antd';
import { getListPage, forceLogout, removeByIds } from '@/services/api/monitor/online';
import { reject } from 'lodash';
import { buildParams, copyObj } from '@/utils/paramUtils';
import { tableSuppert } from '@/utils/response';

const stateValueEnum = {
  0: {
    text: '操作成功',
    status: 'Processing',
  },
  1: {
    text: '操作失败',
    status: 'Error',
  },
};
const bizValueEnum = {
  1: { text: '其他' },
  2: { text: '新增' },
  3: { text: '修改' },
  4: { text: '删除' },
  5: { text: '授权' },
  6: { text: '导出' },
  7: { text: '导入' },
  8: { text: '强退' },
  9: { text: '生成代码' },
  10: { text: '清空数据' },
};
const operatorValueEnum = {
  0: { text: '其他' },
  1: { text: '电脑端' },
  2: { text: '移动端' },
};

export default function logininfor() {
  // 列
  const columns = [
    {
      title: '会话编号',
      dataIndex: 'sessionId',
      key: 'sessionId',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '登录用户名',
      dataIndex: 'username',
      key: 'name',
    },
    {
      title: '设备',
      dataIndex: 'browser',
      key: 'browser',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      key: 'os',
    },
    {
      title: '登录IP',
      dataIndex: 'ipAddr',
      key: 'ipAddr',
    },
    {
      title: '登录地点',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      key: 'showTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            beginTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      width: 100,
      render: (text, record, index, action) => [
        <Space key="action">
          <Popconfirm
            title={() => '您确认要强制退出这个账号吗'}
            onConfirm={() => logout(record.sessionId)}
            okText="Yes"
            cancelText="No"
          >
            <a key="stop">强退</a>
          </Popconfirm>
        </Space>,
      ],
    },
  ];

  //强制退出登录
  const logout = (sessionIds) => {
    forceLogout(sessionIds).then((res) => {
      message.success(res.msg);
    });
  };

  // 查看详情
  const showView = (id) => {
    setOpen(true);
    setId(id);
    setTimeout(() => {
      drawerRef.current.reloadDescriptions();
    });
  };
  //抽屉是否显示
  const [open, setOpen] = useState(false);
  // id值
  const [id, setId] = useState(0); //id
  // 子组件ref
  const drawerRef = useRef(null);

  return (
    <PageContainer content="记录用户登录数据">
      <ProTable
        // 聚焦加载 false
        revalidateOnFocus={false}
        // 等分每列
        tableLayout="fixed"
        // 分页配置
        pagination={{ defaultPageSize: 10, showQuickJumper: true }}
        // 表头
        columns={columns}
        // 发请求
        request={async (param, sorter) => {
          // console.log(sorter);
          let sort = copyObj(sorter);
          if (Object.keys(sort).length === 0) {
            sort.loginTime = 'asc';
          }
          const data = await getListPage(buildParams(param, sort)).then((res) => {
            return res.data;
          });
          return tableSuppert(data);
        }}
        // 选择
        rowSelection={{}}
        // 关键key
        rowKey="sessionId"
        //开启搜索
        search={true}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space size={16}>
              <a>批量删除</a>
              <a>导出数据</a>
            </Space>
          );
        }}
      />
      <ShowDrawer ref={drawerRef} id={id} open={open} setOpen={setOpen.bind(this)} />
    </PageContainer>
  );
}

/**
 * 详情子组件
 */
const ShowDrawer = forwardRef((props, ref) => {
  const detilaRef = useRef();

  // 刷新Descriptions
  const reloadDescriptions = () => {
    detilaRef.current.reload();
  };
  // 绑定函数
  useImperativeHandle(ref, () => ({
    reloadDescriptions,
  }));

  // 关闭抽屉
  const closeDrawer = () => {
    props.setOpen(false);
  };
  // 查询详情
  const getDetials = async () => {
    return new Promise((resolve, reject) => {
      getDetail(props.id)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  return (
    <Drawer title="查看" width="45%" open={props.open} onClose={closeDrawer}>
      <ProDescriptions
        actionRef={detilaRef}
        title="操作日志详情"
        bordered={true}
        request={async () => {
          return await getDetials();
        }}
      >
        <ProDescriptions.Item dataIndex="id" label="编号" span={1.5} />
        <ProDescriptions.Item dataIndex="moduleCode" label="模块编号" span={1.5} />
        <ProDescriptions.Item dataIndex="moduleTitle" label="模块名称" span={1.5} />
        <ProDescriptions.Item dataIndex="requestMethod" label="请求方式" span={1.5} />
        <ProDescriptions.Item dataIndex="username" label="操作用户" span={1.5} />
        <ProDescriptions.Item
          dataIndex="operatorType"
          valueEnum={operatorValueEnum}
          label="操作设备"
          span={1.5}
        />
        <ProDescriptions.Item
          dataIndex="businessType"
          valueEnum={bizValueEnum}
          label="操作业务"
          span={1.5}
        />
        <ProDescriptions.Item dataIndex="operatorTime" label="操作时间" span={1.5} />
        <ProDescriptions.Item
          dataIndex="status"
          label="登录状态"
          valueEnum={stateValueEnum}
          span={1.5}
        />
        <ProDescriptions.Item dataIndex="location" label="操作地点" span={1.5} />
        <ProDescriptions.Item dataIndex="requestUrl" label="请求URL" span={3} />
        <ProDescriptions.Item dataIndex="requestParams" label="请求参数" span={3} />
        <ProDescriptions.Item dataIndex="jsonResult" label="响应结果" span={3} />
        <ProDescriptions.Item dataIndex="errorMsg" label="错误消息" />
      </ProDescriptions>
    </Drawer>
  );
});
